package com.jintu.portal.utils;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.ByteArrayOutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;
import java.util.Map;
import java.util.UUID;
import java.util.zip.Deflater;

/**
 * http请求工具类
 * @author lgh
 *
 */
public class HttpUtils {
	
	private static Logger LOGGER = LoggerFactory.getLogger(HttpUtils.class);

	/**
	 * http post请求
	 * @param jsonObj
	 * @param url
	 * @return
	 */
	public static String httpPostWithJson(String jsonObj,String url){
		String body = "";

	    HttpPost post = null;
	    try {
	        HttpClient httpClient = HttpClients.createDefault();

	        post = new HttpPost(url);
	        // 构造消息头
	        post.setHeader("Content-type", "application/json; charset=utf-8");
	        post.setHeader("Accept", "application/json");
//	        post.setHeader("Connection", "Close");
//	        String sessionId = getSessionId();
//	        post.setHeader("SessionId", sessionId);
//	        post.setHeader("appid", appId);

	        // 构建消息实体
	        StringEntity entity = new StringEntity(jsonObj.toString(), Charset.forName("UTF-8"));
	        entity.setContentEncoding("UTF-8");
	        // 发送Json格式的数据请求
	        entity.setContentType("application/json");
	        post.setEntity(entity);

	        HttpResponse response = httpClient.execute(post);

	        // 检验返回码
	        int statusCode = response.getStatusLine().getStatusCode();
	        if(statusCode != HttpStatus.SC_OK){
	        	LOGGER.info("请求出错: "+ statusCode);
	        }else{

		        //获取结果实体
		        HttpEntity entity1 = response.getEntity();
		        if (entity != null) {
		            //按指定编码转换结果实体为String类型
		            body = EntityUtils.toString(entity1, "UTF-8");
		            LOGGER.info("请求返回JSON数据 >> " + body);
		        }
	        }
	    } catch (Exception e) {
	        e.printStackTrace();
	    }finally{
	        if(post != null){post.releaseConnection();}
	    }
	    return body;
	}

	public static String httpPostWithJsonDeflate(String jsonObj,String url){
		String body = "";

		HttpPost post = null;
		try {
			HttpClient httpClient = HttpClients.createDefault();

			post = new HttpPost(url);
			// 构造消息头
			post.setHeader("Content-type", "application/json; charset=utf-8");
			post.setHeader("Accept", "application/json");
//	        post.setHeader("Connection", "Close");
//	        String sessionId = getSessionId();
//	        post.setHeader("SessionId", sessionId);
//	        post.setHeader("appid", appId);

            /*
            // 构建消息实体
            StringEntity entity = new StringEntity(jsonObj.toString(), Charset.forName("UTF-8"));
            entity.setContentEncoding("UTF-8");
            // 发送Json格式的数据请求
            entity.setContentType("application/json");
            post.setEntity(entity);
            */

			byte [] deflateByte = compress(jsonObj.getBytes());
			ByteArrayEntity bEntity = new ByteArrayEntity(deflateByte);
			bEntity.setContentType("application/json");
			//bEntity.setContentEncoding("UTF-8");
			bEntity.setContentEncoding("deflate");
			post.setEntity(bEntity);
			post.setHeader("Content-Encoding", "deflate");

			HttpResponse response = httpClient.execute(post);

			// 检验返回码
			int statusCode = response.getStatusLine().getStatusCode();
			if(statusCode != HttpStatus.SC_OK){
				LOGGER.info("请求出错: "+ statusCode);
			}else{

				//获取结果实体
				HttpEntity entity1 = response.getEntity();
				if (entity1 != null) {
					//按指定编码转换结果实体为String类型
					body = EntityUtils.toString(entity1, "UTF-8");
					LOGGER.info("请求返回JSON数据 >> " + body);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			if(post != null){post.releaseConnection();}
		}
		return body;
	}

	public static byte[] compress(byte[] inputByte) {
		int len = 0;
		Deflater defl = new Deflater(9, false);
		defl.setInput(inputByte);
		defl.finish();
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		byte[] outputByte = new byte[1024];
		try {
			while (!defl.finished()) {
				// 压缩并将压缩后的内容输出到字节输出流bos中
				len = defl.deflate(outputByte);
				bos.write(outputByte, 0, len);
			}
			defl.end();
		} finally {
			try { bos.close(); } catch (Exception ex) {}
		}
		return bos.toByteArray();
	}

    public static HttpResponse doGet(String host, String path, String method,
                                     Map<String, String> headers,
                                     Map<String, String> querys)
            throws Exception {
        HttpClient httpClient = wrapClient(host);

        HttpGet request = new HttpGet(buildUrl(host, path, querys));
        for (Map.Entry<String, String> e : headers.entrySet()) {
            request.addHeader(e.getKey(), e.getValue());
        }

        return httpClient.execute(request);
    }

    private static HttpClient wrapClient(String host) {
        HttpClient httpClient = new DefaultHttpClient();
        if (host.startsWith("https://")) {
            sslClient(httpClient);
        }

        return httpClient;
    }

    private static void sslClient(HttpClient httpClient) {
        try {
            SSLContext ctx = SSLContext.getInstance("TLS");
            X509TrustManager tm = new X509TrustManager() {
                public X509Certificate[] getAcceptedIssuers() {
                    return null;
                }

                public void checkClientTrusted(X509Certificate[] xcs, String str) {

                }

                public void checkServerTrusted(X509Certificate[] xcs, String str) {

                }
            };
            ctx.init(null, new TrustManager[]{tm}, null);
            SSLSocketFactory ssf = new SSLSocketFactory(ctx);
            ssf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
            ClientConnectionManager ccm = httpClient.getConnectionManager();
            SchemeRegistry registry = ccm.getSchemeRegistry();
            registry.register(new Scheme("https", 443, ssf));
        } catch (KeyManagementException ex) {
            throw new RuntimeException(ex);
        } catch (NoSuchAlgorithmException ex) {
            throw new RuntimeException(ex);
        }
    }

    private static String buildUrl(String host, String path, Map<String, String> querys) throws UnsupportedEncodingException {
        StringBuilder sbUrl = new StringBuilder();
        sbUrl.append(host);
        if (!org.apache.commons.lang3.StringUtils.isBlank(path)) {
            sbUrl.append(path);
        }
        if (null != querys) {
            StringBuilder sbQuery = new StringBuilder();
            for (Map.Entry<String, String> query : querys.entrySet()) {
                if (0 < sbQuery.length()) {
                    sbQuery.append("&");
                }
                if (org.apache.commons.lang3.StringUtils.isBlank(query.getKey()) && !org.apache.commons.lang3.StringUtils.isBlank(query.getValue())) {
                    sbQuery.append(query.getValue());
                }
                if (!org.apache.commons.lang3.StringUtils.isBlank(query.getKey())) {
                    sbQuery.append(query.getKey());
                    if (!StringUtils.isBlank(query.getValue())) {
                        sbQuery.append("=");
                        sbQuery.append(URLEncoder.encode(query.getValue(), "utf-8"));
                    }
                }
            }
            if (0 < sbQuery.length()) {
                sbUrl.append("?").append(sbQuery);
            }
        }

        return sbUrl.toString();
    }

	/**
	 * 构建唯一会话Id
	 * @return
	 */
	public static String getSessionId(){
	    UUID uuid = UUID.randomUUID();
	    String str = uuid.toString();
	    return str.substring(0, 8) + str.substring(9, 13) + str.substring(14, 18) + str.substring(19, 23) + str.substring(24);
	}
	
}
